﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using ITAP.ShprossesBuilder.Modelling.Components;
using ITAP.ShprossesBuilder.Calculations;

namespace ITAP.ShprossesBuilder.Operations
{
    public class OperationCreateShprossChain : IOperation
    {
        #region IOperation Members

        public string Name
        {
            get { return "Объединить профили в цепочку"; }
        }

        public OperationGroup OperationGroup
        {
            get { return OperationGroup.ShprossOperation; }
        }

        public System.Drawing.Image Thumbnail
        {
            get { return null; }
        }

        public void Execute(ModelControl modelControl)
        {
            List<IComponent> shprosses = new List<IComponent>();
            foreach (IComponent component in modelControl.ModelContainer.SelectedComponentsStack)
            {
                if (component is Shpross)
                    shprosses.Add(component);
            }
            if (shprosses.Count <= 1)
                return;

            if (this.CheckChain(shprosses))
            {
                ShprossChain chain = ComponentFactory.CreateShprossChain(shprosses);
                shprosses[0].Parent.AddInnerComponent(chain);
            }
        }

        public bool CanUndo
        {
            get { return true; }
        }

        #endregion

        private bool CheckChain(List<IComponent> shprosses)
        {
            ShprossEndToEndConnector prevEndToEnd = null;
            foreach (Shpross shpross in shprosses)
            {
                if (shpross.Chain != null)
                    return false;

                if (prevEndToEnd == null)
                {
                    if (shpross.StartConnectedComponent is ShprossEndToEndConnector)
                        prevEndToEnd = shpross.StartConnectedComponent as ShprossEndToEndConnector;
                    else if (shpross.EndConnectedComponent is ShprossEndToEndConnector)
                        prevEndToEnd = shpross.EndConnectedComponent as ShprossEndToEndConnector;
                    continue;
                }

                if (shpross.StartConnectedComponent is ShprossEndToEndConnector && 
                    shpross.StartConnectedComponent.IsConnected(prevEndToEnd))
                {
                    prevEndToEnd = shpross.EndConnectedComponent as ShprossEndToEndConnector;
                }
                else if (shpross.EndConnectedComponent is ShprossEndToEndConnector && 
                    shpross.EndConnectedComponent.IsConnected(prevEndToEnd))
                {
                    prevEndToEnd = shpross.StartConnectedComponent as ShprossEndToEndConnector;
                }
                else
                    return false;

            }
            return true;
        }

    }
}

